<?php

class C5AuthUtils
{
    static $debug = false;

    static public function encrypt($params, $remote_user_id, $salt, $debug = "")
    {
        if ($debug != "") {
            self::$debug = $debug;
        }

        $params["remote_user_id"] = $remote_user_id;
        $params["salt"] = $salt;
        ksort($params);
        $string = "" . $salt;
        foreach ($params as $key => $value) {
            if ($key == "remote_verify_code" || $key == "salt") {
                continue;
            }
            if (empty($value)) {
                continue;
            }
            $string .= $key . $value;
        }
        $string .= $salt;
        self::debug("md5的连接串: $string");
        $verifyCode = md5($string);
        self::debug("md5值(verify_code): $verifyCode");
        $params["remote_verify_code"] = $verifyCode;
//        if (array_key_exists("salt", $params)) {
//            unset($params["salt"]);
//        }
//        return $params;
        return $verifyCode;
    }

    static public function do_verify($params, $remote_user_id, $salt, $debug = "")
    {
        if ($debug != "") {
            self::$debug = $debug;
        }

        if (empty($params)) {
            self::debug("没有任何参数 ");
            return false;
        }
        if (!array_key_exists("remote_user_id", $params)) {
            self::debug("缺少参数: remote_user_id ");
            return false;
        }
        if (!array_key_exists("timestamp", $params)) {
            self::debug("缺少参数: timestamp ");
            return false;
        }
        if (!array_key_exists("remote_verify_code", $params)) {
            self::debug("缺少参数: remote_verify_code ");
            return false;
        }
        // 检查时长
        $current_time = self::get_milli_time();
        if (abs($current_time * 1 - $params["timestamp"]) > 500000) {
            self::debug("Timestamp误差错误: " . abs($current_time * 1 - $params["timestamp"]));
            return false;
        }
        $code = $params["remote_verify_code"];
        $md5 = self::encrypt($params, $remote_user_id, $salt, $debug);
        if ($md5 != $code) {
            return false;
        }
        return true;
    }


    static public function get_milli_time()
    {
        $time_test = microtime();
        list($ten_thousand, $sec) = explode(" ", $time_test);
        $time = ((float)$ten_thousand + (float)$sec);
        return round($time * 1000);
    }


    static public function debug($info)
    {
        global $logger;
        if (self::$debug == false) {
            return;
        }
        if (isset($logger)) {
            $logger->debug($info);
        } else {
            echo "<br/>" . $info;
        }

    }

}